# -*- coding:utf-8 -*-
# author:hp
# datetime:18-6-21 下午4:33
# software: PyCharm
from process import Process
import numpy as np
from random import randint


def getRandomAllocation(maxNeed):
    """
    :param maxNeed: numpy.array eg:[5, 4, 4, 6]
    :return: 返回一个每一位都比maxNeed小的随机整数列
    """
    allocation = []
    for i in range(len(maxNeed)):
        allocation.append(randint(0, maxNeed[i]))
    return np.array(allocation)


def List2Str(lst):
    string = ""
    for item in lst:
        string += (item.__repr__() + '\n')
    return string


def safeSeq2Str(lst):
    return " -> ".join(lst)


def isExistSafeSeq(processList, resource):
    processCopyList = processList
    resourceCopy = resource
    safeList = []  # 安全序列
    isExist = False
    for i in range(len(resource)):
        for process in processList:
            # resource可以满足需求
            if False not in (process.need < resource):
                resource = process.alloc(resource)
                processList.remove(process)
                safeList.append(process.name)
                if len(safeList) == len(resource):
                    isExist = True
                    return isExist, safeList, []
    return isExist, processCopyList, resourceCopy


def init(processNum, resourceNum):
    processList = []
    for i in range(processNum):
        maxNeed = np.random.randint(5, 10, (1, resourceNum))[0]
        allocation = getRandomAllocation(maxNeed)
        process = Process("进程{}".format(i+1), maxNeed, allocation)
        processList.append(process)

    resource = np.random.randint(3, 8, (1, resourceNum))[0]
    return processList, resource

# processList, resource = init(4, 4)
# print("logic", List2Str(processList))
# print("logic", resource)
#
# isExist, p, r = isExistSafeSeq(processList, resource)
# if isExist:
#     print("存在安全序列", safeSeq2Str(p))
# else:
#     print("不存在安全序列")
